
<template>
	<view class="bg-white" style="width: 100vw;height: 100vh;">
		<scroll-view scroll-y style="width: 100%;height: 100%;">
			<cu-custom bgColor="bg-white" :isBack="true">
				<block slot="backText"></block>
				<block slot="right">
					<text class="cuIcon-more text-black"></text>
				</block>
			</cu-custom>
			<!-- 播放组件 -->
			<video v-if="currentVideo" style="width: 100vw;" id="myVideo" :src="currentVideo" :initial-time="startTime"
				@timeupdate="updateTime" @loadedmetadata="videoLoaded" @error="videoErrorCallback" @pause="handlePause" controls></video>
			<view class="padding">
				<!-- 课程信息 -->
				<text style="font-size: 32rpx;font-weight: 600;line-height: 50rpx;">{{courseInfo.title}}</text>
				<view class="margin-top" style="font-size: 32rpx;">
					<text class="text-red margin-right">￥{{courseInfo.price}}</text>
					<text class="text-gray">{{courseInfo.buyCount}}人购买</text>
				</view>
				<!-- 好物链接 -->
				<view class="flex justify-between"
					style="margin: 15rpx 32rpx ;padding: 32rpx 32rpx;background: #F2F8FF;border-radius: 8px;"
					v-if="goodLink">
					<image :src="goodLink.cover" mode="aspectFit" style="width: 80rpx; height: 112rpx;"></image>
					<view class="flex flex-direction justify-between">
						<view
							style="width: 480rpx;font-size: 28rpx;font-weight: bold;color: #333333;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
							{{goodLink.title}}
						</view>
						<view class="flex justify-between">
							<view style="font-size: 28rpx;color: #FF3B30;">
								¥{{goodLink.price}}
							</view>
							<view style="font-size: 28rpx;color: #007AFF;">
								购买纸书&nbsp;>
							</view>
						</view>
					</view>
				</view>
				<!-- 视频剧集 -->
				<scroll-view scroll-x style="width: 100%;height: 100%;" :scroll-into-view="toview"
					scroll-with-animation="true">
					<view style="white-space: nowrap;display: inline-flex;">
						<view v-for="(item,index) in courseInfo.courseChapterVos" :key="index" :id="item.num"
							:class="currentCourse==index? 'course course-active':'course'" @click="chooseCourse(index)">
							<text :class="currentCourse==index?'title title-active':'title'">{{item.title}}</text>
							<text class="time">{{item.gmtModified.slice(0,11)}}更新</text>
						</view>
					</view>
				</scroll-view>
				<!-- 作者信息 -->
				<view class="flex align-center margin-top justify-between ">
					<!-- 头像 姓名 -->
					<view class=" flex align-center"
						@click="$Router.push({name:'profile',params:{authorId:courseInfo.teacherId}})">
						<view class="cu-avatar round margin-right-xs"
							:style="{'background-image':'url(' + courseInfo.avatar + ')'}"></view>
						<text class="text-gray" style="font-weight: 500;">{{courseInfo.teacherUsername}}</text>
					</view>
					<!-- 是否关注 -->
					<view>
						<button
							:class="[isFollow?'cu-btn block bg-grey margin-tb-sm':'cu-btn block bg-blue margin-tb-sm']"
							style="width: 150rpx; height: 60rpx;" @click="follow()">{{isFollow?'已关注':'关注'}}</button>
					</view>
				</view>
				<!-- 作者简介 -->
				<text class="text-gray"
					style="display: -webkit-box;overflow: hidden;-webkit-box-orient:vertical; -webkit-line-clamp:2;">
					{{courseInfo.teacherDescription}}
				</text>
				<!-- 课程详情 -->
				<view class="margin-top">
					<view style="font-size: 32rpx;font-weight: 600;" class="text-black margin-bottom">课程详情</view>
					<rich-text :nodes="courseInfo.courseDescription"></rich-text>
				</view>
				<!-- 评论 -->
				<comment v-if="showComment" :comment-list="commentList" type-name="课程" @publish="handlePublish">
				</comment>
				<!-- 其他课程 -->
				<view class="margin-top">
					<view class="flex align-center justify-between margin-bottom-xl">
						<text class="text-black" style="font-size: 32rpx;font-weight: 600;">其他课程</text>
						<text class="text-blue" style="font-size: 32rpx;font-weight: 600;"
							@click="expand">{{isall?'收起':'查看全部'}}</text>
					</view>
					<view v-for="(item,index) in temp" :key="index" class="margin-top">
						<singlecell :books="item"></singlecell>
					</view>
				</view>
			</view>
			<!-- 占位区 -->
			<view style="height: 125rpx"></view>
			<!-- 购买按钮 -->
			<view style="position: fixed;bottom: 0;z-index: 2000;width: 100%;" class="bg-white">
				<view v-if="!hasPurchased" class="flex justify-center">
					<button @click="goToPay()" class="cu-btn bg-blue margin-tb-sm"
						style="width: 500rpx; height: 85rpx;">立即购买</button>
				</view>
				<view v-if="hasPurchased" class="flex align-center">
					<!-- 评论 -->
					<view class=" flex-sub flex flex-direction align-center margin-top-sm ">
						<text @click="toggleMask('show')" class="text-black cuIcon-comment "
							style="font-size: 50rpx;"></text>
						<text>{{commentList.length}}</text>
					</view>
					<!-- 收藏 -->
					<view class="flex-sub  flex flex-direction  align-center margin-top-sm">
						<text :class="[isFavorite?' text-blue cuIcon-likefill':'text-black cuIcon-like']"
							@click="favorite()" style="font-size: 50rpx;"></text>
						<text>{{favoriteCount}}</text>
					</view>
				</view>
			</view>

		</scroll-view>
		<ygc-comment ref="ygcComment" :placeholder="'发布评论'" @pubComment="pubComment">
		</ygc-comment>
	</view>
</template>

<script>
	const TypeCourse = '2';
	import {
		mapActions
	} from "vuex";
	import comment from '../../components/comment/comment.vue';
	import ygcComment from '../../components/comment/ygc-comment.vue';
	import articleApi from '../../api/articleApi.js';
	import cuCustom from '../../plugin/colorui/components/cu-custom.vue'
	import singlecell from '../../components/column/singlecell.vue'
	export default {
		components: {
			comment,
			ygcComment,
			cuCustom,
			singlecell
		},
		data() {
			return {
				user: {},
				showComment: false,
				constantID: "0000000000000000000",
				targetComment: {},
				commentList: [],
				currentVideo: "", //当前页面的视频
				currentTime: 0,
				courseId: this.$Route.query.id ? this.$Route.query.id : '1192252213659774977',
				isall: false, //是否查看全部
				isFollow: false,
				isFavorite: false,
				favoriteCount: 0,
				currentCourse: 0,
				toview: "",
				temp: [], //otherCourse的备份数组
				courseInfo: {},
				goodLink: null,
				hasPurchased: false,
				otherCourse: [{
						cover: "https://ftp.bmp.ovh/imgs/2021/04/30ea9cc3d2a4730b.jpg",
						title: "英语发音与语法",
						price: "199",
						buyCount: 1000
					},
					{
						cover: "https://ftp.bmp.ovh/imgs/2021/04/30ea9cc3d2a4730b.jpg",
						title: "英语发音与语法",
						price: "199",
						buyCount: 1000
					}
				]
			}
		},
		onReady: function(res) {
			// #ifndef MP-ALIPAY
			this.videoContext = uni.createVideoContext('myVideo')
			// #endif
		},
		onLoad() {
			this.user.id = this.$store.getters.userid;
			this.temp = this.otherCourse.slice(0, 2) //其他课程列表收缩
			// 获取课程详情
			this.$http.get('/edu/course/getCourseInfo/' + this.courseId + '/' + this.user.id).then((res) => {
				// console.log("courseData", res);
				let data = res.data;
				if(data.success) {
					this.courseInfo = res.data.result
					this.courseInfo.courseChapterVos.forEach((item) => {
						item.num = "a" + item.id //配置scroll-to-view
					})
					if(this.courseInfo.courseChapterVos[0]) {
						this.startTime = this.courseInfo.courseChapterVos[0].currentTime;
					} else {
						this.startTime = 0.0;
					}
					this.currentVideo = this.courseInfo.courseChapterVos[0].videoUrl;
					this.isFollow = res.data.result.isFollow;
					this.hasPurchased = res.data.result.hasPurchased;
					this.isFavorite = res.data.result.hasFavorite
					this.favoriteCount = res.data.result.favoriteCount
				} else {
					this.$tip.error("课程信息获取失败，请检查网络");
				}
			})
			// 获取商品链接
			this.$http.get('/edu/course/getCourseBuyLink/' + this.courseId).then(res => {
				if (res.data.success) {
					this.goodLink = res.data.result;
				} else {
					this.goodLink = null;
				}
			})
			// 评论
			this.targetComment = {};
			articleApi.getArticleComment([this.courseId, TypeCourse]).then(res => {
				this.commentList = res.data;
				this.showComment = true;
			})
		},
		onUnload() {
			this.updateLearnRecord();
		},
		methods: {
			...mapActions(["savePage"]),
			videoErrorCallback: function(e) {
				console.log("video play error");
			},
			handlePause(e) {
				console.log("pause");
			},
			updateLearnRecord() {
				this.$http.post("/edu/learn-record/updateLearnRecord", {
					"authorId": this.courseInfo.teacherId,
					"columnType": TypeCourse,
					"contentId": this.courseId,
					"contentSubject": this.courseInfo.courseChapterVos[this.currentCourse].id,
					"currentTime": this.currentTime,
					"totalTime": this.duration,
					"learnedTime": this.currentTime,
					"userId": this.user.id
				}).then(res => {
					let data = res.data;
					if (!data.success) {
						console.log("更新学习记录失败")
					}
				})
			},
			updateTime(e) {
				this.currentTime = e.detail.currentTime;
			},
			videoLoaded(e) {
				this.duration = e.detail.duration;
			},
			chooseCourse(index) {
				this.currentCourse = index;
				this.toview = this.courseInfo.courseChapterVos[index].num;
				this.startTime = this.courseInfo.courseChapterVos[index].currentTime;
				this.currentVideo = this.courseInfo.courseChapterVos[index].videoUrl;
				
				//更新学习记录
				this.updateLearnRecord();
			},
			goToPay() {
				this.$http.post(`/eduorder/order/createCourseOrder/${this.courseId}`).then((res) => {
					let data = res.data; //data中的result是订单编号outTradeNo
					if (data.success) {
						//跳转前保存当前页面
						const page = {
							name: 'courseDetail',
							params: {
								courseId: this.courseId,
							}
						};
						this.savePage(JSON.stringify(page));
						// console.log("outTradeNo", data.result)
						this.$Router.push({
							name: 'orderConfirm',
							params: {
								outTradeNo: data.result
							}
						})
					} else {
						this.$tip.error(data.message); //已支付该课程, 刷新当前页面
						this.$Router.replace({
							name: 'courseDetail',
							params: {
								courseId: this.courseId,
							}
						})
					}
				}).catch((err) => {
					console.log(err);
				})
			},
			favorite() {
				this.isFavorite = !this.isFavorite;
				if (this.isFavorite) { //收藏
					this.favoriteCount++;
					this.$http.post('/edu/favorite/favoriteContent', {
						contentId: this.courseId,
						userId: this.user.id,
						columnType: '2'
					}).then(res => {
						let data = res.data;
						if (data.success) {
							this.$tip.success(data.message)
						} else {
							this.$tip.error("收藏失败！");
							this.isFavorite = !this.isFavorite;
							this.favoriteCount--;
						}
					}).catch(err => {
						console.log(err);
						this.$tip.error("收藏失败！");
						this.isFavorite = !this.isFavorite;
						this.favoriteCount--;
					});
				} else { //取消收藏
					this.favoriteCount--;
					this.$http.post('/edu/favorite/unfavoriteContent', {
						contentId: this.courseId,
						userId: this.user.id,
						authorId: this.courseInfo.teacherId,
						columnType: '2'
					}).then(res => {
						let data = res.data;
						if (data.success) {
							this.$tip.success(data.message)
						} else {
							this.$tip.error("取消收藏失败！");
							this.isFavorite = !this.isFavorite;
							this.favoriteCount++;
						}
					}).catch(err => {
						console.log(err);
						this.$tip.error("取消收藏失败！");
						this.isFavorite = !this.isFavorite;
						this.favoriteCount++;
					});
				}
			},
			follow() {
				this.isFollow = !this.isFollow;
				if (this.isFollow) { //与粉丝没有互关，点击后关注粉丝unfollowOne
					this.$http.post("/ucenter/follow/followOne", {
						userId: this.user.id,
						followedId: this.courseInfo.teacherId
					}).then(res => {
						let data = res.data;
						if (data.success) {
							this.$tip.success(data.message)
						}
					}).catch(err => {
						console.log(err);
					});
				} else { //与粉丝互关，点击后取关粉丝
					this.$http.post("/ucenter/follow/unfollowOne", {
						userId: this.user.id,
						followedId: this.courseInfo.teacherId
					}).then(res => {
						let data = res.data;
						if (data.success) {
							this.$tip.success(data.message)
						}
					}).catch(err => {
						console.log(err);
					});
				}

			},
			expand() {
				if (!this.isall) {
					this.temp = this.otherCourse.slice(0, this.otherCourse.length)
				} else {
					this.temp = this.otherCourse.slice(0, 2)
				}
				this.isall = !this.isall
			},
			toggleMask(type) {
				this.$refs.ygcComment.toggleMask(type);
			},
			handlePublish: function(item) {
				this.targetComment = item;
				this.toggleMask("show");
			},
			pubComment(commentContent) {
				this.$refs.ygcComment.toggleMask();
				this.$refs.ygcComment.content = '';
				let constantID = this.constantID;
				//向后端添加评论
				let comment = {
					userId: this.user.id,
					parentCommentId: JSON.stringify(this.targetComment) == "{}" ? constantID : (this.targetComment
						.parentCommentId == constantID ? this.targetComment.commentId : this.targetComment
						.parentCommentId),
					targetCommentId: JSON.stringify(this.targetComment) == "{}" ? constantID : (this.targetComment
						.parentCommentId == constantID ? constantID : this.targetComment.commentId),
					targetUserId: JSON.stringify(this.targetComment) == "{}" ? '' : (this.targetComment
						.parentCommentId == constantID ? '' : this.targetComment.userId),
					contentId: this.courseId,
					columnType: TypeCourse,
					content: commentContent
				}
				articleApi.addComment(comment).then(res => {
					this.$tip.success('评论成功!');
					this.$Router.replace({
						name: 'courseDetail',
						params: {
							id: this.courseId
						}
					})
				})
			},
		}
	}
</script>

<style>
	#myVideo {
		width: 100%;
	}

	.course {
		border-radius: 10rpx;
		padding: 10rpx;
		width: 290rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		margin-top: 25rpx;
		margin-right: 20rpx;
		border: #dddddd solid 4rpx;
	}

	.title {
		flex: 1;
		color: #AAAAAA;
		font-size: 30rpx;
		overflow: hidden;
		white-space: normal;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
	}

	.time {
		margin-top: 20rpx;
		color: #AAAAAA;
	}

	.course-active {
		border: rgba(0, 122, 255, 1) solid 4rpx;
	}

	.title-active {
		color: rgba(0, 122, 255, 1);
	}
</style>

